package com.easylinkin.linkappapi.common.translate.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.easylinkin.linkappapi.common.translate.Code2Text;
import com.easylinkin.linkappapi.common.translate.CodeTranslateor;
import com.easylinkin.linkappapi.common.translate.CodeTranslateorFactory;
import com.easylinkin.linkappapi.common.translate.TypeEnum;
import com.easylinkin.linkappapi.space.entity.LinkappArea;
import com.easylinkin.linkappapi.space.mapper.LinkappAreaMapper;
import com.easylinkin.linkappapi.space.vo.SpaceTreeVo;

/**
 * 空间翻译器
 * @author OYGD
 *
 */
@Component
public class SpaceTranslate implements CodeTranslateor {
	
	@Autowired
	private LinkappAreaMapper mapper;
	
	Map<String, SpaceTreeVo> cache = new HashMap<>();
	
	@PostConstruct
	public void init() {
		CodeTranslateorFactory.register(this.getClass(), this);
		
		List<SpaceTreeVo> selectLinkappAreaTreeList = mapper.selectLinkappAreaTreeList(new LinkappArea());
		for (SpaceTreeVo vo : selectLinkappAreaTreeList) {
			cache.put(vo.getId(), vo);
		}
	}
	
	public void cache() {
		cache.clear();
		List<SpaceTreeVo> selectLinkappAreaTreeList = mapper.selectLinkappAreaTreeList(new LinkappArea());
		for (SpaceTreeVo vo : selectLinkappAreaTreeList) {
			cache.put(vo.getId(), vo);
		}
	}

	@Override
	public String translate(Object obj, Object value, Code2Text ann) {
		if (null == value) {
			return null;
		}
		if (ann.type() == TypeEnum.SPILT) {
			List<?> list = (List<?>) value;
			StringBuilder sb = new StringBuilder();
			for (Object id : list) {
				sb.append(this.getName(id.toString())).append("/");
			}
			return sb.toString();
		} else {
			return this.getName(value.toString());
		}
	}
	
	String getName(String id) {
		SpaceTreeVo vo = cache.get(id);
		if(vo != null) {
			return vo.getName();
		}
		return "";
	}

}
